package com.yc.snack.filter;


import com.yc.snack.util.ConstantInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 后台过滤器
 */
@WebFilter(value = "/back/manager/*", filterName = "CheckLoginFilter")
public class CheckLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取session，从session中获取登录的管理员信息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Object obj = request.getSession().getAttribute(ConstantInfo.CURRENTLOGINADMIN);

        // 判空，如果为空，则直接返回。当前请求到此结束
        if (obj == null) {
            response.setContentType("text/html;charset=utf8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请先登录...');location.href='" + request.getContextPath() +"/back/login.html'</script>");
            out.flush();
            return;
        }

        // 如果满足则交给下一个过滤器
        filterChain.doFilter(request, response);
    }
}
